<template>
  <view class="wrapper">
    <u-navbar
      :title="$t('user.Favorites')"
      :autoBack="false"
      bgColor="#F6F6F6"
      titleStyle="font-weight: 500; color: #000000;"
      :placeholder="true"
      @leftClick="gotoBack"
    >
    </u-navbar>
    <u-swipe-action v-if="collectList && collectList.length > 0">
      <u-swipe-action-item
        style="margin-top: 20upx; border-radius: 20upx"
        :options="options1"
        v-for="(item, index) in collectList"
        :key="index"
        @click="handleSelect(item.messageCollectId)"
      >
        <view class="box">
          <!-- 语音 -->
          <view class="content-text" v-if="item.messageType == 'RC:HQVCMsg'">
            <!-- 语音信息 -->
            <view
              class="chart-voice connect-block-right"
              @tap="playVoice(item)"
            >
              <view
                class="progress-background"
                :style="
                  item.context.progress
                    ? `width: ${item.context.progress}%`
                    : 'width: 0'
                "
              ></view>
              <view
                class="iconfont icon-bofang voice-icon voice-icon-shadow"
                v-show="!item.context.progress"
              ></view>
              <image
                src="@/static/image/chart/play-right.png"
                class="play-right"
                v-show="item.context.progress"
              />
              <view class="iconfont icon-jindutiao progress-icon"></view>
              <text>{{ item.context.duration }}''</text>
            </view>
          </view>
          <!-- 文本信息 -->
          <view
            class="content-text"
            v-if="
              item.messageType == 'RC:TxtMsg' ||
              item.messageType === 'OL:Recall'
            "
            @click="gotoTextDetail(item)"
          >
            <rich-text :nodes="item.context.content"></rich-text>
          </view>
          <!-- 图片信息 -->
          <view class="content-text" v-if="item.messageType == 'RC:ImgMsg'">
            <image
              :src="item.context.imageUri"
              @click="showPreview(item.context.imageUri)"
              class="ImgMsg"
							mode="aspectFill"
							v-if="!item.context.mediaExpansion"
            />
						<rich-text v-else :nodes="showMediaWithText(item)" @click="gotoTextDetail(item)"></rich-text>
          </view>
					<!-- 视频信息 -->
          <view class="content-text" v-if="item.messageType == 'RC:SightMsg'">
						<view class="ImgMsg" style="width: fit-content;" v-if="!item.context.mediaExpansion">
							<j-video
								:ref="`video-${index}`"
								:danmu-btn="true"
								:controls="false"
								:url="item.context.sightUrl"
								:poster="item.context.content"
								height="200upx"
							/>
							<!-- <rich-text :nodes="item.context.content"></rich-text> -->
							<view class="iconfont icon-bofang1" @click="openVideo(`video-${index}`)"></view>
						</view>
						<rich-text v-else :nodes="showMediaWithText(item)" @click="gotoTextDetail(item)"></rich-text>
          </view>
          <!-- 文件信息 -->
          <view
            class="content-text to-flex"
            v-if="item.messageType === 'RC:FileMsg' && !item.context.mediaExpansion"
            @click="favoClick(item)"
          >
            <view class="left-icon">
              <view class="iconfont icon-wenjian"></view>
            </view>
            <!-- 右侧文件类型信息 -->
            <view class="file-content">
              <div class="file-content">
              <div class="file-name">
                <div class="name-left omit">
                  {{ getFileNameCut(item.context.name, "first") }}
                </div>
                <div>{{ getFileNameCut(item.context.name, "last") }}</div>
              </div>
              <div class="file-size">{{ getSize(item.context.size) }}</div>
            </div>
            </view>
          </view>
					<view v-else-if="item.messageType === 'RC:FileMsg' && item.context.mediaExpansion" class="content-text">
						<rich-text :nodes="showMediaWithText(item)" @click="gotoTextDetail(item)"></rich-text>
					</view>

          <view class="content-info">
            <view>{{ item.sendName }}</view>
            <view>{{ item.sendTime }}</view>
          </view>
        </view>
      </u-swipe-action-item>
    </u-swipe-action>
    <u-empty
      v-else
      :text="$t('favority.EmptyDataList')"
      textColor="#878787"
      textSize="14"
      width="104"
      height="100"
      marginTop="160"
      icon="/static/image/bourse/none_order.png"
    >
    </u-empty>
    <u-loadmore
      :loadingText="$t('contacts.loading')"
      nomoreText="nomore"
      marginTop="30rpx"
      marginBottom="0"
      :status="status"
      v-if="status == 'loading'"
    />
  </view>
</template>

<script>
import {
  queryMessageCollectList,
  queryMessageCollectDelete,
} from "@/services/chat";
import { isJsonStr } from "@/utils/util";
import JVideo from "@/uni_modules/j-video/components/j-video/j-video.vue";
import { downloadWebViewFlie } from '@/utils/olImInterface.js'
export default {
  name: "Favorites",
	components: {
    JVideo,
  },
  data() {
    return {
      isHiddenControl: false, // 是否显示视频底部控制组件
      collectList: [],
      options1: [
        {
          icon: "icon-shanchu3",
          iconStyle: {
            fontSize: "40upx",
            color: "#FFFFFF",
          },
          // text: "删除",
          style: {
            background: "#FE6600",
            width: "90upx",
            height: "90upx",
            borderRadius: "50%",
            marginLeft: "40upx",
          },
        },
      ],
      params: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      status: "none",
      // 上一条播放语音的消息
      previousVodieMsg: null,
      innerAudioContext: null,
      vidieProgressTimer: null,
    };
  },
  filters: {
    textLenthToEllipsis(str) {
      // 大于24个字符则做省略号处理
      let last;
      let first;
      let resultStr;
      if (str.length > 17) {
        last = str.slice(-1);
        first = str.slice(0, -13);
        resultStr = first + "..." + last;
        return resultStr;
      }
      return str;
    },
  },
  onPullDownRefresh() {
    this.params.pageNum = 1;
    this.status = "none";
    this.handleCollectList();
  },
  onReachBottom() {
    if (this.params.pageNum * this.params.pageSize >= this.total) {
      this.status = "nomore";
      return;
    }
    this.status = "loading";
    this.params.pageNum++;
    this.handleCollectList();
  },
  methods: {
		// 获取媒体文件带文字的类型展示
    showMediaWithText (item) {
      let msg = ''
      switch (item.messageType) {
        case 'RC:ImgMsg':
          msg = '[photo]' + (item.context.mediaExpansion ? (' ' + item.context.mediaExpansion) : '')
          break
        case 'OL:Recall':
        case 'RC:TxtMsg':
        case 'RC:SightMsg':
          msg = '[video]' + (item.context.mediaExpansion ? (' ' + item.context.mediaExpansion) : '')
          break
        case 'RC:FileMsg':
          msg = '[file]' + (item.context.mediaExpansion ? (' ' + item.context.mediaExpansion) : '')
          break
        case 'RC:HQVCMsg':
        default:
          break
      }
      return msg
    },
		openVideo(ref) {
			this.$refs[ref][0].state = true
		},
    // 返回上一页
    gotoBack() {
      uni.switchTab({
        url: "/pages/user/User",
      });
    },
    // 跳转文本详情页
    gotoTextDetail(item) {
      console.log(item);
      uni.navigateTo({
        url: "/pagesUser/favorites/TextDetail",
        success: function (res) {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit("TextDetail", {
            data: item,
          });
        },
      });
    },
    // 播放语音功能
    playVoice(item) {
      if (
        this.previousVodieMsg &&
        item.sendSiteId === this.previousVodieMsg.sendSiteId
      ) {
        item.context.progress = 0;
        this.previousVodieMsg = null;
        this.stopPlayVoice();
        return;
      }
      var mp3Url = item.context.remoteUrl;
      this.$set(item.context, "progress", 0);
      if (
        this.innerAudioContext &&
        !this.innerAudioContext.paused &&
        this.previousVodieMsg
      ) {
        this.previousVodieMsg.context.progress = 0;
        item.context.progress = 0;
        this.stopPlayVoice();
      }
      this.innerAudioContext = uni.createInnerAudioContext();
      this.innerAudioContext.autoplay = true;
      this.innerAudioContext.src = mp3Url; //音频地址
      this.innerAudioContext.play(); //执行播放
      this.innerAudioContext.onCanplay(async () => {
        let multiple = 0;
        this.vidieProgressTimer = setInterval(() => {
          multiple =
            this.innerAudioContext.duration == Infinity
              ? 100 / item.context.duration
              : 100 / this.innerAudioContext.duration;
          console.log(
            "播放了",
            this.innerAudioContext.duration,
            item.context.duration,
            multiple
          );
          item.context.progress = this.innerAudioContext.currentTime * multiple;
          if (
            this.innerAudioContext.currentTime >=
            this.innerAudioContext.duration
          ) {
            window.clearInterval(this.vidieProgressTimer);
            this.vidieProgressTimer = null;
            item.context.progress = 0;
          }
        }, 10);
      });
      this.previousVodieMsg = item;
    },
    // 暂停语音播放
    stopPlayVoice() {
      if (this.vidieProgressTimer) {
        window.clearInterval(this.vidieProgressTimer);
        this.vidieProgressTimer = null;
      }
      if (this.innerAudioContext) {
        this.innerAudioContext.stop();
        this.innerAudioContext.destroy();
        this.innerAudioContext = null;
      }
    },
    // 下载文件
    downloadFile(item) {
      console.log("下载文件", item);
      // 如果点击的是视频就不需要下载视频
      // if (item.context?.type === "video/mp4") return false;
      if (this.$store.state.isWebview) {
        downloadWebViewFlie(item.context?.fileUrl, item.context?.name)
        return
      }
      // #ifdef H5
      let platform = uni.getSystemInfoSync();
      if (platform.platform == "ios") {
        window.location.href = item.context?.fileUrl;
        return
      }
      // 以下操作只针对docx文档下载和音频下载
      const link = document.createElement("a");
      // 这里是将链接地址url转成blob地址，
      fetch(item.context?.fileUrl)
        .then((res) => res.blob())
        .then((blob) => {
          link.href = URL.createObjectURL(blob);
          // 下载文件的名称及文件类型后缀
          link.download = item.context?.name;
          document.body.appendChild(link);
          link.click();
          // 在资源下载完成后 清除 占用的缓存资源
          window.URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        });
      // #endif
    },
    // 点击文件类型
    favoClick(item) {
      switch (item.messageType) {
        // case 'OL:Recall':
        // case 'RC:TxtMsg':
        //   break
        // case 'RC:ImgMsg':
        //   this.currentUrl = item.context?.imageUri
        //   this.previreShow = true
        //   break
        // case 'RC:SightMsg':
        //   this.currentUrl = item.context?.sightUrl
        //   this.previreShow = true
        //   break
        case "RC:FileMsg":
          this.downloadFile(item);
          break;
        default:
          break;
      }
    },
    // 点击遮罩层打开视频播放器
    touchMaskVideo(videoId) {
      let videoContext = uni.createVideoContext(videoId, this);
      this.isHiddenControl = false;
      videoContext.requestFullScreen();
    },
    // 点击播放
    play(e) {
      let videoContext = uni.createVideoContext(e.target.id, this);
      videoContext.requestFullScreen();
    },
    // 退出播放
    fullscreenchange(e) {
      console.log(e.detail.fullScreen);
      if (!e.detail.fullScreen) {
        uni.createVideoContext(e.target.id, this).pause();
        this.isHiddenControl = true;
      }
    },
    // 点击预览图片
    showPreview(url) {
      uni.previewImage({
        urls: [url],
      });
    },
    async handleCollectList() {
      const resp = await queryMessageCollectList({
        orderByColumn: "updateTime",
        isAsc: "desc",
        ...this.params,
      });
      this.status = "none";
      uni.stopPullDownRefresh();
      console.log(resp, "cee");
      if (resp.result.code != 200) return;
      this.total = resp.result.total;
      const newData =
        resp.result.rows.map((element) => {
          // 判断是否为json格式的数据
          if (isJsonStr(element.context)) {
            element.context = JSON.parse(element.context);
          } else {
            element.context = {
              content: element.context,
            };
          }
          return element;
        }) || [];

      this.params.pageNum == 1
        ? (this.collectList = newData)
        : (this.collectList = [...this.collectList, ...newData]);

      console.log(this.collectList);
    },
    async handleSelect(id) {
      const resp = await queryMessageCollectDelete(id);
      if (resp.result.code != 200) return;
      this.handleCollectList();
    },
    getFileNameCut (fName, cutType) {
      // console.log(fName.substring(0, fName.length - 8))
      // console.log(fName.substring(fName.length - 8, fName.length))
      if (fName.length > 8) {
        if (cutType === 'first') {
          return fName.substring(0, fName.length - 8)
        } else if (cutType === 'last') {
          return fName.substring(fName.length - 8, fName.length)
        }
      } else {
        if (cutType === 'first') {
          return fName
        } else if (cutType === 'last') {
          return ''
        }
      }
    },
    /** 换算文件大小 */
    getSize(size) {
      if (!size) return "0K";
      var num = 1024.0; // byte
      if (size < num) return size + "B";
      if (size < Math.pow(num, 2)) return (size / num).toFixed(2) + "K"; // kb
      if (size < Math.pow(num, 3)) {
        return (size / Math.pow(num, 2)).toFixed(2) + "M";
      } // M
      if (size < Math.pow(num, 4)) {
        return (size / Math.pow(num, 3)).toFixed(2) + "G";
      } // G
      return (size / Math.pow(num, 4)).toFixed(2) + "T"; // T
    },
  },
  onLoad() {
    this.handleCollectList();
  },
  onHide() {
    this.stopPlayVoice();
  },
};
</script>

<style lang="scss" scoped>
/deep/ .u-loadmore__content__text {
  height: 32rpx;
}
::v-deep .playIcon {
	display: none;
}

.omit {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  word-wrap: break-word;
  white-space: pre-line;
  word-break: break-all;
}

.wrapper {
  // 视频播放器
  .myVideo {
    width: 200upx;
    height: 200upx;

    // background: #000000;
    // /deep/ .uni-video-container .uni-video-cover .uni-video-cover-play-button {
    //   width: 76upx;
    //   height: 76upx;
    //   border: 6upx solid #fff;
    //   border-radius: 50%;
    //   box-shadow: 0px 0px 6px 0px rgba(0,0,0,0.1);
    // }
    /deep/ .uni-video-container .uni-video-cover .uni-video-cover-duration {
      display: none;
    }
  }

  .isHiddenControl {
    /deep/ .uni-video-container .uni-video-bar.uni-video-bar-full {
      display: none;
    }
  }

  .mask-video {
    position: absolute;
    z-index: 99;
    top: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 1;

    .mask-video-border {
      width: 76upx;
      height: 76upx;
      border-radius: 50%;
      box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.1);
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      border: 6upx solid #fff;
    }
  }

  box-sizing: border-box;
  padding: 0 30rpx 30rpx;

  .box {
    margin-top: 20upx;
    width: 100%;
    background: #ffffff;
    border-radius: 20upx;
    box-sizing: border-box;
    padding: 0 30upx;

    .to-flex {
      display: flex !important;
      align-items: center;
    }

    .content-text {
      box-sizing: border-box;
      // padding: 30upx 0;
      margin: 30upx 0; // overflow隐藏不了内边距的内容，改用外边距
      font-size: 28upx;
      font-weight: 400;
      color: #000000;
      line-height: 44upx;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      // border-bottom: 2upx solid #f6f6f6;
      word-break: break-all; // 强制换行
      overflow: hidden;

      .left-icon {
        width: 44px;
        height: 44px;
        background: #61bdb2;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;

        .icon-wenjian {
          font-size: 26px;
          color: #ffffff;
        }
      }

      .file-content {
        margin-left: 13px;
        flex: 1;
        padding: 4px 0px 1px;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        flex-direction: column;

        .file-name {
          width: 100%;
          display: flex;
          font-size: 14px;
          font-family: Source Han Sans CN;
          font-weight: 400;
          color: #000000;
          white-space: nowrap;
          display: flex;

          .name-left {
            -webkit-line-clamp: 1 !important;
            line-clamp: 1 !important;
          }
        }

        .file-size {
          font-size: 12px;
          font-family: Source Han Sans CN;
          font-weight: 400;
          color: #878787;
          margin-top: 5px;
        }
      }
    }

    .ImgMsg {
      width: 200upx;
      height: 200upx;
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;
			.icon-bofang1 {
				font-size: 76upx;
				color: #ffffff;
				border-radius: 50%;
				box-shadow: 0upx 0upx 6upx 0upx rgba(0,0,0,0.1);
				position: absolute;
			}
    }

    .content-info {
      border-top: 2upx solid #f6f6f6;
      height: 70upx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 24upx;
      font-weight: 400;
      color: #878787;
    }
  }
}

/deep/ .u-swipe-action-item__content {
  border-radius: 10px;
}

.chart-voice {
  overflow: hidden;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  width: 360rpx;
  height: 78rpx;
  background: #61bdb2;
  border-radius: 39rpx;
  color: #ffffff;

  .progress-background {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    border-radius: 20rpx 0px 0px 20rpx;
    background-color: #e6f5f3;
  }

  .video-back-box {
    display: inherit;
    background-color: #fff;
    z-index: 10;
    border-radius: 50%;
    box-shadow: 0px 0px 16rpx 0px rgba(75, 145, 250, 0.3);
  }

  .voice-icon {
    z-index: 10;
    font-size: 48rpx;
  }

  .voice-icon-shadow {
    box-shadow: 0px 0px 16px 0px rgba(62, 165, 152, 0.5);
  }

  .progress-icon {
    z-index: 10;
    font-size: 32rpx;
    margin: 0 40rpx 0 20rpx;
  }

  text {
    z-index: 10;
    font-size: 28rpx;
    font-family: HarmonyOS Sans-Regular, HarmonyOS Sans;
    font-weight: 400;
    line-height: 40rpx;
  }
}

.play-right {
  width: 48upx;
  height: 48upx;
}
</style>